<?php
namespace app\common\model;
use think\model\concern\SoftDelete;
use think\Validate;

class Article extends Common
{
    const STATUS_YES = 1; // 是否推荐 热门 发布 状态开启
    const STATUS_NO = 2; //                  状态关闭
    use SoftDelete;
    //时间自动存储
    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    //软删除位
    protected $deleteTime = 'isdel';

    //验证规则
    protected $rule = [
        'title' => 'require|max:200',
        'content' => 'require',
        'type_id' => 'require',
        'sort' => 'number'
    ];

    protected $msg = [
        'title.require' => '文章标题必须填写',
        'title.max' => '标题名称最多不能超过200个字符',
        'content.require' => '文章内容必须填写',
        'type_id.require' => '请选择文章分类',
        'sort.number' => '排序必须是数字类型'
    ];

    /**
     * @param $post
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit']))
        {
            $limit = $post['limit'];
        }
        else
        {
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        $list = $this->with('articleType')
            ->where($tableWhere['where'])
            ->order($tableWhere['order'])
            ->paginate($limit);
        $data = $this->tableFormat($list->getCollection()); //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;
        return $re;
    }


    /**
     * 添加文章数据 方法
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];
        $validate = new Validate($this->rule, $this->msg);
        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        }
        else
        {
            $articleTypeModel = new ArticleType();
            $data['codes'] = $articleTypeModel->where('id', $data['type_id'])->value('codes');
            if(!$this->allowField(true)->save($data))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }


    /**
     * 文章编辑更新
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];

        $validate = new Validate($this->rule,$this->msg);

        if(!$validate->check($data))
        {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        }
        else
        {
            if(!$this->allowField(true)->save($data,['id'=>$data['id']]))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }


    /**
     * 搜索条件
     * @param $post
     * @return mixed
     */
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['title']) && $post['title'] != "")
        {
            $where[] = ['title', 'like', '%'.$post['title'].'%'];
        }
        if(isset($post['utime']) && $post['utime'] != "")
        {
            $date_array = explode('~', $post['utime']);
            $sutime = strtotime($date_array[0].'00:00:00', time());
            $eutime = strtotime($date_array[1].'23:59:59', time());
            $where[] = ['utime', ['EGT', $sutime], ['ELT', $eutime], 'and'];
        }
        if(isset($post['type_id']) && $post['type_id'] != "")
        {
            $where[] = ['type_id', 'eq', $post['type_id']];
        }
        if(isset($post['is_pub']) && $post['is_pub'] != "")
        {
            $where[] = ['is_pub', 'eq', $post['is_pub']];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['sort ASC'];
        return $result;
    }


    protected function tableFormat( $list )
    {
        foreach($list as $val)
        {
            $val['ctime'] = getTime($val['ctime']);
            $val['utime'] = getTime($val['utime']);
        }
        return $list;
    }


    /**
     * 获取文章列表
     * @param $type_id
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function articleList($type_id = null, $where = [], $page = 1, $limit = 10)
    {
        $result = [
            'status' => true,
            'msg' => '获取成功',
            'data' => []
        ];

        $field = 'id,cover,title,content,ctime,utime,read_amount';

        if ($where) {
            if ($where['is_hot']) $where[] = ['is_hot', 'eq', self::STATUS_YES];
            if ($where['is_rec']) $where[] = ['is_rec', 'eq', self::STATUS_YES];
        }

        if ($type_id) {
            $where[] = ['type_id', 'eq', $type_id];
        }

        $where[] = ['is_pub', 'eq', self::STATUS_YES];

        $list = $this->field($field)
            ->where($where)
            ->order('ctime desc')
            ->page($page, $limit)
            ->select();

        if (!$list->isEmpty())
        {
            foreach ($list as $key => &$value) {
                $value['cover'] = _sImage($value['cover']);
                $value['content'] = htmlSpecialFormat($value['content']);
                $value['ctime'] = date('Y-m-d', $value['ctime']);
                $value['utime'] = date('Y-m-d', $value['utime']);
            }

            $count = $this->where($where)->count();
            $result['data']['list'] = $list->toArray();
            $result['data']['count'] = $count;
        }

        return $result;
    }



    /**
     *  获取文章详情
     */
    public function articleDetail($article_id = null)
    {
        $result = [
            'status' => false,
            'msg' => '获取失败',
            'data' => []
        ];
        if(!$article_id)
        {
            return error_code(11001);
        }


        $field = 'id,title,content,ctime,utime';

        $where[] = ['id', 'eq', $article_id];
        $where[] = ['is_pub', 'eq', self::STATUS_YES];

        $data = $this->field($field)
            ->where($where)
            ->find();

        if($data)
        {
            $data['ctime'] = getTime($data['ctime']);
            $data['utime'] = getTime($data['utime']);
            $result['status'] = true;
            $result['msg'] = '获取成功';
            $result['data'] = $data;
        }
        return $result;
    }



    /**
     *  文章阅读量增加
     */
    public function setArticleReadAmount($article_id = null)
    {
        $result = [
            'status' => true,
            'msg' => '',
            'data' => []
        ];

        if ($article_id)
        {
            $this->where('id', $article_id)->setInc('read_amount');
        }

        return $result;
    }


    /**
     * @return \think\model\relation\HasOne
     */
    public function articleType()
    {
        return $this->hasOne('ArticleType', 'id', 'type_id')->bind(['type_name']);
    }
}